package main

import (
	"net"
	"fmt"
	"strconv"
)

func main() {

	server, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Println(err)
		return
	}

	queue := make(chan net.Conn, 1)

	i := 0
	for {
		conn, err := server.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}

		i++
		fmt.Println("建立新连接")
		go inQueue(queue, conn)
		go deQueue(queue)
		//go handle(conn, i)

	}
}

var index = 0
func inQueue(queue chan net.Conn, conn net.Conn) {
	queue <- conn
}

func deQueue(queue chan net.Conn) {
	conn := <- queue
	index++
	handle(conn, index)
}

func handle(conn net.Conn, i int) {
	count := 0
	for {
		conn.Write([]byte("hi client"))
		receive := make([]byte, 100)
		length,_ := conn.Read(receive)

		if(length > 0) {
			fmt.Println(i, "收到数据：" + string(receive))

			count += 1
			conn.Write([]byte("hi client " + strconv.Itoa(count)))
		}

	}
}
